package servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;

import mongo.CourseClass;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(description = "managercourseclassProcess", urlPatterns = { "/manager/courseclass/managercourseclassServlet" })
public class managerCourseClassServlet extends HttpServlet{
	private CourseClass CourseClass = new CourseClass();
	HttpSession session = null;
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
	    session = request.getSession();
		
		String method = request.getParameter("method");
		if(method.equals("delete")){
			this.delete(request, response);
		}else if(method.equals("manageradd")){
			this.manageradd(request, response);
		}else if(method.equals("managerlist")){
			this.managerlist(request, response);
		}else if(method.equals("managerupdate")){
			this.managerupdate(request, response);
		}else if(method.equals("managerbatchadd")){
			this.managerbatchadd(request, response);
		}else if(method.equals("managerquery")){
			this.managerquery(request, response);
		}else{
//			request.getRequestDispatcher("404.jsp").forward(request, response); 添加错误页面
		}
	}
	
	
	public void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        try {
    		ObjectId _id = new ObjectId(request.getParameter("_id"));
    		Boolean result = CourseClass.delete(_id);
    		if(result) {
				this.managerlist(request, response);
			}
    		//TODO针对返回结果和所属模块，返回到相对应的页面  
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	
	
	public void managerlist(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
    		MongoCursor<Document> result = CourseClass.managerlist();
    		request.setAttribute("result", result);
    	    request.getRequestDispatcher("courseclasslist.jsp").forward(request, response);
    		//TODO针对所属模块，返回到相对应的页面   
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }

	}
	
	
	
	public void manageradd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Boolean result = null ;
		try{
			Enumeration<String> names = request.getParameterNames();
			Document newcourseclass = new Document();
			while(names.hasMoreElements()){
				String name = names.nextElement();
				String value = request.getParameter(name);
				if(value == null){
					value = "无";
				}
				newcourseclass.append(name, value);
			}
			Document yearSemester = (Document)session.getAttribute("yearSemester");
			newcourseclass.append("year", yearSemester.getString("year"));
			newcourseclass.append("semester", yearSemester.getString("semester"));
			if(CourseClass.isExist(newcourseclass.getString("coursecode"))){
				
			}else{
				if(CourseClass.add(newcourseclass)){
					this.managerlist(request, response);
				}else{
					
				}
			}
			//TODO针对返回结果和所属模块，返回到相对应的页面
		}catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            //TODO发生异常,跳转到对应页面
        }
	}
	
	public void managerbatchadd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	String filename = request.getParameter("filename");
        	String fileDir = this.getServletContext().getRealPath("/upload") +"/"+ filename; //获取路径
        	Document yearSemester = (Document)session.getAttribute("yearSemester");
        	List<String> errresult = CourseClass.batchAdd(fileDir,yearSemester);
    		MongoCursor<Document> result = CourseClass.managerlist();
    		request.setAttribute("errresult", result);
    		request.setAttribute("result", result);
    	    request.getRequestDispatcher("courseclasslist.jsp").forward(request, response);
        	//TODO根据添加的童虎类型返回相应的list
        	
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	public void managerupdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	ObjectId _id = new ObjectId(request.getParameter("_id"));
        	Document updateDocument = new Document();
        	Enumeration<String> names = request.getParameterNames();
        	while(names.hasMoreElements()){
        		String name = names.nextElement();
        		String value = request.getParameter(name);
        		if(value==null){
        			updateDocument.append(name, "无");
        		}else{
                    updateDocument.append(name, value);
        		}
        	}
    		Boolean result = CourseClass.update(_id, updateDocument);
    		if(result) {
    			this.managerlist(request, response);
    		}
        	//TODO得到结果，跳转到显示页面，如果更新的用户是使用者，则更新session
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	public void managerquery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String queryname = request.getParameter("name");
    	String queryvalue = request.getParameter("value");
    	if(queryvalue.equals("")) {
    		this.managerlist(request, response);
    	}
    	else {
    		BasicDBObject queryDBobject = new BasicDBObject(queryname,queryvalue);
        	MongoCursor<Document> result = CourseClass.query(queryDBobject);
        	request.setAttribute("queryname", queryname);
        	request.setAttribute("queryvalue", queryvalue);
        	request.setAttribute("result", result);
        	request.getRequestDispatcher("courseclasslist.jsp").forward(request, response);
    	}
	}
	
	
}
